<template>
    <div class="table-mechanism">
        <div class="tableHeader">
            <el-input style="width: 200px; margin-right: 20px;" @change="search()" v-model.trim="queryForm.elderlyCode" autocomplete="off" placeholder="请输入入住人编号或姓名"></el-input>
            <el-date-picker
                v-model="checkedInTime"
                @change="val => { queryForm.checkedInTimeStart = val && val[0]; queryForm.checkedInTimeEnd = val && val[1]; search() }"
                type="daterange"
                range-separator="至"
                start-placeholder="入住开始日期"
                end-placeholder="入住结束日期">
            </el-date-picker>
        </div>
        <el-table :data="list" v-loading="listLoading">
            <el-table-column show-overflow-tooltip="" min-width="100" label="入住编号" prop="checkInMark"></el-table-column>
            <el-table-column show-overflow-tooltip="" min-width="150" label="老人编号" prop="elderlyCode"></el-table-column>
            <el-table-column prop="elderlyName" label="老人姓名" min-width="100"></el-table-column>
            <el-table-column label="入住日期" min-width="120">
                <template slot-scope="scope">
                        {{scope.row.checkedInTime | parseTime('{y}-{m}-{d}')}}
                </template>
            </el-table-column>
            <el-table-column label="床位地址" min-width="160">
                <template slot-scope="scope">
                        {{ scope.row.buildingNumber }}-{{ scope.row.floor }}-{{ scope.row.unit }}-{{ scope.row.roomNumber }}
                </template>
            </el-table-column>
            <el-table-column label="护理级别" min-width="100px" prop="nursingLevelName"></el-table-column>
            <el-table-column min-width="160px" label="备注" prop="remark"></el-table-column>
            <el-table-column label="操作" prop="disabled" min-width="100px" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" @click="planVisible = true; activeRow = scope.row; getPlanlist()">
                        训练计划
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            :background="background"
            :current-page=queryForm.currPageNo
            :total="total"
            :page-size="queryForm.limit"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        ></el-pagination>

        <el-dialog
            title="训练计划"
            :visible.sync="planVisible"
            width="700px"
        >
            <div class="header">
                <el-button @click="openAddPlan()">添加训练计划</el-button>
            </div>
            <br>
            <div class="planlist">
                <el-table
                    :data="planlist"
                    v-loading="planlistLoading"
                >
                    <el-table-column
                        prop="planName"
                        label="计划名称"
                    ></el-table-column>
                    <el-table-column  label="执行日期"  width="150">
                        <template slot-scope="scope">
                            {{scope.row.startDate | parseTime('{y}-{m}-{d}')}}
                        </template>
                    </el-table-column>
                    <el-table-column  label="终止日期"  width="150">
                        <template slot-scope="scope">
                            <span v-if="scope.row.expirationDate">{{scope.row.expirationDate | parseTime('{y}-{m}-{d}')}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" prop="disabled"  width="150px"  fixed="right">
                        <template slot-scope="scope">
                            <el-button type="text" @click="addPlanVisible = true; planIsEdit = true; addPlanform = {...scope.row};">编辑</el-button>
                            <el-button type="text" @click="projectVisible = true; activePlanRow = scope.row; getProjectlist(1)">训练记录</el-button>
                            <!-- <el-button type="text" @click="projectVisible = true; activePlanRow = scope.row; getProjectlist(2)">套餐外项目</el-button> -->
                            <!-- <el-button type="text" v-if="!scope.row.disabled" @click="enablePlan(scope.row.planNumber, scope.row.disabled)">禁用</el-button>
                            <el-button type="text" v-else @click="enablePlan(scope.row.planNumber, scope.row.disabled)">启用</el-button> -->
                            <!-- <el-button type="text" @click="delPlan(scope.row.planNumber)">删除</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                    :background="background"
                    :current-page=planQueryForm.currPageNo
                    :total="planTotal"
                    :page-size="planQueryForm.limit"
                    @current-change="planHandleCurrentChange"
                    @size-change="planHandleSizeChange"
                ></el-pagination>
            </div>
        </el-dialog>

        <el-dialog
            :title="planIsEdit ? '修改训练计划' : '添加训练计划'"
            :visible.sync="addPlanVisible"
            width="600px"
        >
            <el-form ref="addPlanform" :model="addPlanform" :rules="planRules" label-width="120px" >
                <el-form-item label="病史摘要" prop="aaaa">
                    <el-input v-model="addPlanform.aaaa" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="病功能独立性评估结论史摘要" prop="bbbb">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" v-model="addPlanform.bbbb" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="康复训练计划" prop="cccc">
                    <el-input v-model="addPlanform.cccc" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="康复训练目标" prop="dddd">
                    <el-input v-model="addPlanform.dddd" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="康复训练项目" prop="eeee">
                    <el-select
                        style="width: 100%;"
                        v-model="addPlanform.eeee"
                        multiple
                        placeholder="请选择康复训练项目">
                        <el-option
                            v-for="item in trainList"
                            :key="item.dcNo"
                            :label="item.name"
                            :value="item.dcNo">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="功能独立性评估结论" prop="startDate">
                    <el-date-picker
                        v-model="addPlanform.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="终止日期">
                    <el-date-picker
                        v-model="addPlanform.expirationDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addPlanVisible = false" >取 消</el-button>
                <el-button type="primary" @click="savePlan">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="训练记录"
            :visible.sync="projectVisible"
            width="1000px"
        >
            <div class="header">
                <el-button @click="searchProjectInside()">添加训练记录</el-button>
            </div>
            <br>
            <div class="planlist">
                <el-table
                    :data="projectlist"
                    v-loading="projectlistLoading"
                >
                    <el-table-column
                        show-overflow-tooltip
                        label="项目名称"
                        prop="nursingItemName"
                    ></el-table-column>
                    <el-table-column label="是否收费">
                        <template slot-scope="scope">
                            {{ scope.row.charge ? '是' : '否'}}
                        </template>
                    </el-table-column>
                    <el-table-column label="执行费用">
                        <template slot-scope="scope">
                            {{ scope.row.price }}
                        </template>
                    </el-table-column>
                    <el-table-column label="执行周期">
                        <template slot-scope="scope">
                            {{ scope.row.unit == 2 ? '月' : '天'}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        label="执行周期间隔"
                        width="120"
                        prop="cycle"
                    ></el-table-column>
                    <el-table-column label="计划开始时间"  width="180">
                        <template slot-scope="scope" v-if="scope.row.startExecTime">
                            {{ scope.row.startExecTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="终止时间"  width="180">
                        <template slot-scope="scope" v-if="scope.row.expirationDate">
                            {{ scope.row.expirationDate | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" prop="disabled"  width="120px"  fixed="right">
                        <template slot-scope="scope">
                            <!-- <el-button type="text" @click="planVisible = true">套餐项目</el-button>
                            <el-button type="text">套餐外项目</el-button>
                            <el-button type="danger" @click="enablePlan(id, scope.row.state)">禁用</el-button> -->
                            <el-button type="text" @click="editProject({ ...scope.row })">编辑</el-button>
                            <el-button type="text" v-if="!scope.row.disabled" @click="enableProject(false, { ...scope.row })">禁用</el-button>
                            <el-button type="text" v-else @click="enableProject(true, { ...scope.row })">启用</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- <el-pagination
                    :background="background"
                    :current-page=projectQueryForm.currPageNo
                    :total="projectTotal"
                    :page-size="projectQueryForm.limit"
                    @current-change="projectHandleCurrentChange"
                    @size-change="projectHandleSizeChange"
                ></el-pagination> -->
            </div>
        </el-dialog>

        <el-dialog
            :title="isEditProject ? '编辑训练记录' : '添加训练记录'"
            :visible.sync="addProjectVisibleInside"
            width="560px"
        >
            <el-form ref="addProjectFormInside" :model="addProjectFormInside" :rules="addProjectRulesInside" label-width="140px" >
                <el-form-item label="训练日期" prop="a1a1">
                    <el-date-picker
                        v-model="addProjectFormInside.a1a1"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="训练次数" prop="b1b1">
                    <el-input-number v-model="addProjectFormInside.b1b1" :min="0" :max="99999"></el-input-number>
                </el-form-item>
                <el-form-item label="训练项目" prop="c1c1">
                    <el-select
                        v-model="addProjectFormInside.c1c1"
                        placeholder="请选择训练项目">
                        <el-option
                            v-for="item in trainList"
                            :key="item.dcNo"
                            :label="item.name"
                            :value="item.dcNo">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="训练时间" prop="d1d1">
                    <el-date-picker
                        v-model="addProjectFormInside.d1d1"
                        type="datetime"
                        placeholder="请选择训练时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="训练情况记录" prop="e1e1">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" v-model="addProjectFormInside.e1e1" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="康复员" prop="f1f1">
                    <search-input v-model="addProjectFormInside.f1f1" :config="sConfig" @change="executorChange" placeholder="请输入并选择康复员"></search-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addProjectVisibleInside = false" >取 消</el-button>
                <el-button type="primary" @click="addProjectInside">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { searchCheckinInfoOfCondition, nurseplanAdd, nurseplanUpdate, searchNursePlansOfConditions, nurseplanDisable, nurseplanEnable, nurseplanRemove, searchNursePlanItem, searchmeal, addMealItemToPlan, modifyMealNursePlanItem, disableOrEnableNursePlanItem } from "@/api/record"

    import { parseTime} from "@/utils/index";
    import searchInput from '@/components/searchInput'
    export default {
        name: "Record",
        filters:{
            parseTime: parseTime
        },
        components: {
            searchInput
        },
        data() {
            return {
                sConfig: {
                    api: 'sinohis/pension/nurse/dailycare/searchExecutor',
                    method: 'post',
                    postKey: 'name',
                    label: 'name',
                    value: 'number',
                    data: { institutionNumber: JSON.parse(localStorage.getItem("institutionNumber")) },
                    keys: [
                        { name: '姓名', key: 'name' },
                        { name: '类型', key: 'typeName' },
                    ]
                },
                searchName: '',
                searchValue: '',
                checkedInTime: [],
                listLoading: true,
                total: 0,
                planTotal: 0,
                background: true,
                id: 0,
                list: [],
                planVisible: false,
                planIsEdit: false,
                addPlanVisible: false,
                planlist: [],
                planlistLoading: false,
                addPlanform: {
                    eeee: []
                },
                activeRow: {},
                projectVisible: false,
                activePlanRow: {},
                addProjectVisible: false,
                queryForm: {
                    currPageNo: 1,
                    limit: 10,
                    elderlyCode: '',
                    checkedInTimeStart: '',
                    checkedInTimeEnd: '',
                },
                planQueryForm: {
                    currPageNo: 1,
                    limit: 10,
                },
                projectQueryForm: {
                    // currPageNo: 1,
                    // limit: 10,
                },
                projectlist: [],
                projectlistLoading: false,
                projectTotal: 0,
                addProjectValue: '',

                planRules: {
                    aaaa: [
                        { required: true, message: '不能为空', trigger: 'blur' },
                    ],
                    bbbb: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    cccc: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    dddd: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    eeee: [
                        { type: 'array', required: true, message: '不能为空', trigger: 'change' }
                    ],
                },
                searchProjectLoading: false,
                searchProjectOptions: [],
                addProjectForm: {},
                addProjectRules: {
                    itemMark: [
                        { required: true, message: '请选择项目', trigger: 'change' }
                    ],
                    unit: [
                        { required: true, message: '请选择执行周期单位', trigger: 'change' }
                    ],
                    cycle: [
                        { required: true, message: '请输入间隔数', trigger: 'change' }
                    ],
                    executionTimes: [
                        { type: 'array', required: true, message: '请选择周期内执行时间', trigger: 'change' }
                    ],
                    startExecTime: [
                        { required: true, message: '请选择开始时间', trigger: 'change' }
                    ],
                },
                addProjectVisible: false,
                addProjectVisibleInside: false,
                searchProjectOptionsInside: [],
                addProjectFormInside: {
                    executionTimes: []
                },
                addProjectRulesInside: {
                    a1a1: [
                        { required: true, message: '请选择训练日期', trigger: 'change' }
                    ],
                    b1b1: [
                        { required: true, message: '请输入训练次数', trigger: 'change' }
                    ],
                    c1c1: [
                        { required: true, message: '请选择训练项目', trigger: 'change' }
                    ],
                    d1d1: [
                        { required: true, message: '请选择训练时间', trigger: 'change' }
                    ],
                    e1e1: [
                        { required: true, message: '请填写训练情况', trigger: 'blur' }
                    ],
                    f1f1: [
                        { required: true, message: '请选择康复员', trigger: 'change' }
                    ],
                },
                activeProjectlRow: {},
                activeProjectlRow1: {},
                isEditProject: false,
                trainList: [],
                executorType: '',
            };
        },
        created(){
            this.queryForm.institutionNumber= JSON.parse(localStorage.getItem("institutionNumber"));
            this.search()
            this.trainList = JSON.parse(localStorage.getItem("dictionary")).find(item => item.mark == 'train').childs
        },
        methods: {
            search(){
                this.listLoading = true;
                searchCheckinInfoOfCondition(this.queryForm).then(res =>{
                    this.list = res.data.data
                    this.total = res.data.total
                    setTimeout(() => {
                        this.listLoading = false;
                    }, 50);
                })
            },
            handleSizeChange(val) {
                this.queryForm.limit = val;
                this.search();
            },
            handleCurrentChange(val) {
                this.queryForm.currPageNo = val;
                this.search();
            },
            planHandleSizeChange(val) {
                this.planQueryForm.limit = val;
                this.getPlanlist();
            },
            planHandleCurrentChange(val) {
                this.planQueryForm.currPageNo = val;
                this.getPlanlist();
            },
            projectHandleSizeChange(val) {
                this.planQueryForm.limit = val;
                this.getProjectlist();
            },
            projectHandleCurrentChange(val) {
                this.planQueryForm.currPageNo = val;
                this.getProjectlist();
            },
            close(){
                this.dialogFormVisible = false;
            },
            openAddPlan(){
                this.addPlanVisible = true;
                this.planIsEdit = false;
                this.addPlanform = {
                    eeee: []
                }
                this.$nextTick(() => {
                    this.$refs['addPlanform'].clearValidate();
                })
            },
            getPlanlist(){
                this.planlistLoading = true
                this.planQueryForm.checkInMark = this.activeRow.checkInMark
                searchNursePlansOfConditions(this.planQueryForm).then((res) => {
                    this.planlist = res.data.data || []
                    this.planTotal = res.data.total
                    setTimeout(() => {
                        this.planlistLoading = false;
                    }, 50);
                })
            },
            savePlan(){
                this.$refs['addPlanform'].validate(async (valid) => {
                    if (valid) {
                        this.addPlanform.checkInIdentify = this.activeRow.checkInMark
                        if(this.planIsEdit){
                            nurseplanUpdate(this.addPlanform).then(res => {
                                this.addPlanVisible = false
                                this.getPlanlist()
                            })
                        }else{
                            nurseplanAdd(this.addPlanform).then(res => {
                                this.addPlanVisible = false
                                this.planQueryForm.currPageNo = 1
                                this.getPlanlist()
                            })
                        }
                    }
                })
            },
            enablePlan(planNumber, state){
                if(!state){
                    nurseplanDisable({planNumber}).then(res => {
                        this.getPlanlist()
                    })
                }else{
                    nurseplanEnable({planNumber}).then(res => {
                        this.getPlanlist()
                    })
                }
            },
            delPlan(planNumber){
                this.$baseConfirm("你确定要删除当前项吗", null, async () => {
                    const {code, msg } = await nurseplanRemove({planNumber});
                    if(code==200){
                        this.$baseMessage("删除成功");
                        this.getPlanlist()
                    }else {
                        this.$baseMessage("删除失败");
                    }
                });
            },
            getProjectlist(type){
                this.projectlistLoading = true
                this.projectQueryForm.planNumber = this.activePlanRow.planNumber
                searchNursePlanItem(this.projectQueryForm).then((res) => {
                    this.projectlist = res.data
                    // this.projectTotal = res.data.total
                    setTimeout(() => {
                        this.projectlistLoading = false;
                    }, 50);
                })
            },
            addProjectInside(){
                // this.isEditProject = false
                this.$refs['addProjectFormInside'].validate(async (valid) => {
                    if (valid) {
                        let times = [...this.addProjectFormInside.executionTimes]
                        let timeList = []
                        let timeString = []
                        for(let i=0; i<times.length; i++){
                            let item = times[i]
                            let itemList = []
                            itemList.push(item.d >= 0 ? item.d : null)
                            itemList.push(item.h >= 0 ? item.h : null)
                            itemList.push(item.m >= 0 ? item.m : null)
                            timeList.push(itemList)
                            let timeStringItem = (item.d >= 0 ? item.d : 0) + '' + item.h + '' + item.m

                            if(timeStringItem.length > 6){
                                this.$baseMessage('执行时间不能为空', 'error')
                                return false
                            }
                            timeString.push(timeStringItem)
                        }
                        if(Array.from(new Set(timeString)).length < timeString.length){
                            this.$baseMessage('执行时间不能重复', 'error')
                            return false
                        }
                        let addForm = {...this.addProjectFormInside}
                        addForm.executionTimes = timeList
                        addForm.mealMark = this.activeRow.mealCode
                        addForm.planNumber = this.activePlanRow.planNumber
                        if(this.isEditProject){
                            modifyMealNursePlanItem(addForm).then(res => {
                                this.getProjectlist()
                                this.addProjectVisibleInside = false
                            })
                        }else{
                            addMealItemToPlan(addForm).then(res => {
                                this.getProjectlist()
                                this.addProjectVisibleInside = false
                            })
                        }
                    }
                })
            },
            searchProjectInside(){
                this.isEditProject = false
                searchmeal({ checkInMark: this.activeRow.checkInMark }).then(res => {
                    this.searchProjectOptionsInside = res.data.items
                })
                this.addProjectVisibleInside = true;
                this.addProjectFormInside = {
                    executionTimes: [{}]
                }
                this.$nextTick(() => {
                    this.$refs['addProjectFormInside'].clearValidate();
                })
            },
            executorChange(row){
                this.executorType = row.type
            },
            delTimeItem(index){
                this.addProjectFormInside.executionTimes.splice(index, 1)
            },
            delTimeItem1(index){
                this.addProjectForm.executionTimes.splice(index, 1)
            },
            editProject(row){
                this.isEditProject = true
                let isInside = row.mealItem

                if(isInside){
                    searchmeal({ checkInMark: this.activeRow.checkInMark }).then(res => {
                        this.searchProjectOptionsInside = res.data.items
                    })
                    this.addProjectVisibleInside = true;
                }else{
                    // this.searchProject(row.nursingItemName)
                    this.searchName = row.nursingItemName
                    this.searchValue = row.nursingItemMark
                    this.addProjectVisible = true;
                }

                let a = row.executionTimes
                a = a.substring(0, a.length - 1)
                a = a.split('&')
                let c = []
                a.forEach(item => {
                    let b = {}
                    let d = item.split('-')
                    b.d = parseInt(d[0])
                    b.h = parseInt(d[1])
                    b.m = parseInt(d[2])
                    c.push(b)
                })
                row.executionTimes = c
                row.itemMark = row.nursingItemMark

                if(isInside){
                    this.addProjectFormInside = row
                }else{
                    this.addProjectForm = row
                }
            },
            enableProject(type, row){
                let isInside = row.mealItem
                disableOrEnableNursePlanItem({ enableStatus: type, planItemNumber: row.planItemNumber }).then(res => {
                    this.getProjectlist()
                })
            }
        }
    }
</script>

<style scoped>
    .timeBox{margin-bottom: 10px;}
    .timeBox:last-child{margin-bottom: 0;}
    .timeBox i{cursor: pointer;color: #1890ff;margin-left: 10px;}
    .itemBox{}
    .itemBox span{display: inline-block;overflow: hidden; white-space: nowrap; text-overflow: ellipsis;width: 120px;}
    .itemBox span:first-child{width: 130px;}

    .table-mechanism >>> .el-table .warning-row {background: oldlace;opacity: 0.5;}
    .table-mechanism >>> .el-table .success-row {background: #f0f9eb;}
    .tableHeader{padding:20px 10px;}
</style>
